package com.kvn.fx;

import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.util.StringUtils;

public class Controller {
    @FXML
    private TextField f_expression;
    @FXML
    private TextField f_class;
    @FXML
    private TextField f_method;
    @FXML
    private Button btn_check;
    @FXML
    private Text t_rlt;

    /**
     * 开始检测 onAction事件
     */
    public void checkExpression() {
        String expression = this.f_expression.getText();
        String clazz = this.f_class.getText();
        String method = this.f_method.getText();
        if (StringUtils.hasText(method) == false) {
            method = "defaultMethod"; // pointcut exp就是用来匹配到方法级别的，如果用户没有输入方法名，就赋默认值
        }
        System.out.println("expression:" + expression);
        System.out.println("clazz:" + clazz);
        System.out.println("method:" + method);
        Class clazzNeedCheck = generateClassAndMethod(clazz, method);
        try {
            doCheck(expression, clazzNeedCheck, method);
        } catch (Exception e) {
            e.printStackTrace();
            fillResultText(e.getMessage());
        }
    }

    private Class generateClassAndMethod(String className, String methodName) {
        return AsmCodeGenerateUtil.generateClassAndMethod(className, methodName);
    }

    private void doCheck(String expression, Class clazz, String method) {
        AspectJExpressionPointcut aspectJExpressionPointcut = new AspectJExpressionPointcut();
        aspectJExpressionPointcut.setExpression(expression);
        boolean classMatches = aspectJExpressionPointcut.getClassFilter().matches(clazz); // 这里使用的是快速匹配，跟pointcut表达式关系不是很大
        System.out.println("matched:" + classMatches);
        boolean methodMatches = false;
        try {
            methodMatches = aspectJExpressionPointcut.getMethodMatcher().matches(clazz.getDeclaredMethod(method), clazz);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        System.out.println("methodMatches:" + methodMatches);

        StringBuffer rltMsg = new StringBuffer("结果：\r\n");
        rltMsg.append("匹配结果==》" + (classMatches && methodMatches));

        fillResultText(rltMsg.toString());
    }

    private void fillResultText(String msg){
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                //更新JavaFX的主线程的代码放在此处
                t_rlt.setText(msg);
            }
        });
    }
}
